package com.campol;

import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;

import com.campol.activity.HomeScreenActivity;
import com.campol.activity.MapScreenActivity;
import com.campol.activity.MoreActivity;
import com.campol.activity.PostsListingActivity;
import com.campol.activity.SettingsActivity;
import com.campol.extlogger.ExtLogger;
import com.campol.http.ServiceManager;
import com.campol.model.PostModel;
import com.campol.model.Reporter;
import com.campol.utils.Constants;
import com.campol.utils.CustomXmlParser;
import com.campol.utils.UserPreferences;
import com.campol.view.TabBarButton;

public class MainActivity extends TabActivity implements OnClickListener,
		LocationListener, OnTabChangeListener {

	private static final String TAG = "MainActivity";
	private static int currentTag = 0;

	private static final int DLG_CANCEL_REGISTRATION = 0;
	private static final int DLG_ACCESS_DENIED = 1;

	public static final String TAB_HOME = "home";
	public static final String TAB_LISTING = "listing";
	public static final String TAB_MAP = "map";
	public static final String TAB_SETTINGS = "settings";
	public static final String TAB_MORE = "more";

	private static final int A_MINUTE = 1000 * 60;
	private LocationManager mlManager;
	private ArrayList<PostModel> posts = null;
	private ArrayList<Reporter> reporters = null;

	private ProgressDialog pdBar;

	public interface OnPostListChangedListener {
		void onPostListChanged(ArrayList<PostModel> items);
	}

	public interface OnPostItemSelectedListener {
		void onPostItemSelected(PostModel item);
	}

	public interface OnReporterChangedListener {
		void onReporterChanged(ArrayList<Reporter> items);
	}

	private ArrayList<OnPostListChangedListener> observers = null;
	private OnPostItemSelectedListener postItemSelListener = null;
	private OnReporterChangedListener reporterListener = null;
	private PostModel tempPost;

	private ScrollView regstrForm;
	private TableLayout tabBar;
	private EditText etEmail, etPassword, etConfirm, etFirstname, etLastname,
			etLoginEmail, etLoginPassword;
	private LinearLayout llLoginContainer, llRegContainer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tabs);

		regstrForm = (ScrollView) findViewById(R.id.registration_form);
		llLoginContainer = (LinearLayout) findViewById(R.id.login_container);
		llRegContainer = (LinearLayout) findViewById(R.id.registration_container);
		findViewById(R.id.reg_btn_cancel).setOnClickListener(this);
		findViewById(R.id.reg_btn_register).setOnClickListener(this);
		findViewById(R.id.login_btn).setOnClickListener(this);
		findViewById(R.id.register_btn).setOnClickListener(this);
		etLoginEmail = (EditText) findViewById(R.id.login_useremail);
		etLoginPassword = (EditText) findViewById(R.id.login_password);
		etEmail = (EditText) findViewById(R.id.reg_useremail);
		etPassword = (EditText) findViewById(R.id.reg_password);
		etConfirm = (EditText) findViewById(R.id.reg_confirm);
		etFirstname = (EditText) findViewById(R.id.reg_firstname);
		etLastname = (EditText) findViewById(R.id.reg_lastname);

		tabBar = (TableLayout) findViewById(R.id.bottom_bar);

		pdBar = new ProgressDialog(this);
		pdBar.setIndeterminate(true);
		pdBar.setTitle("Loading");
		pdBar.setMessage("Updating list...");
		pdBar.setCancelable(false);

		Log.d(TAG, "trying to set up tab buttons");
		// set up tabs buttons
		TabBarButton tabHome = (TabBarButton) findViewById(R.id.tab_home);
		Log.d(TAG, "tabHome = " + tabHome);
		tabHome.setButtonText("Home");
		tabHome.setButtonIcon(R.drawable.home_icon);
		tabHome.setOnClickListener(this);

		TabBarButton tabListing = (TabBarButton) findViewById(R.id.tab_listing);
		tabListing.setOnClickListener(this);
		tabListing.setButtonText("List");
		tabListing.setButtonIcon(R.drawable.list_icon);

		TabBarButton tabMap = (TabBarButton) findViewById(R.id.tab_map);
		tabMap.setOnClickListener(this);
		tabMap.setButtonText("Map");
		tabMap.setButtonIcon(R.drawable.map_icon);

		TabBarButton tabSettings = (TabBarButton) findViewById(R.id.tab_settings);
		tabSettings.setOnClickListener(this);
		tabSettings.setButtonText("Settings");
		tabSettings.setButtonIcon(R.drawable.settings_icon);

		TabBarButton tabMore = (TabBarButton) findViewById(R.id.tab_more);
		tabMore.setOnClickListener(this);
		tabMore.setButtonText("More");
		tabMore.setButtonIcon(R.drawable.more_icon);

		// set up tab controller
		TabHost tabHost = getTabHost();
		tabHost.addTab(tabHost.newTabSpec(TAB_HOME).setIndicator("0")
				.setContent(new Intent(this, HomeScreenActivity.class)));
		tabHost.addTab(tabHost.newTabSpec(TAB_LISTING).setIndicator("1")
				.setContent(new Intent(this, PostsListingActivity.class)));
		tabHost.addTab(tabHost.newTabSpec(TAB_MAP).setIndicator("2")
				.setContent(new Intent(this, MapScreenActivity.class)));
		tabHost.addTab(tabHost.newTabSpec(TAB_SETTINGS).setIndicator("3")
				.setContent(new Intent(this, SettingsActivity.class)));
		tabHost.addTab(tabHost.newTabSpec(TAB_MORE).setIndicator("4")
				.setContent(new Intent(this, MoreActivity.class)));

		getTabHost().setCurrentTab(currentTag);
		int tabId = R.id.tab_home;
		if (currentTag == 1)
			tabId = R.id.tab_listing;
		else if (currentTag == 2)
			tabId = R.id.tab_map;
		else if (currentTag == 3)
			tabId = R.id.tab_settings;
		else if (currentTag == 4)
			tabId = R.id.tab_more;
		((TabBarButton) findViewById(tabId)).setTabButtonPressed(true);

		mlManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (UserPreferences.getUserEmail(this) != null) {
			regstrForm.setVisibility(View.GONE);
			// make request for token or check if it is valid
			new GetTokenTask().execute();
		} else {

			// TODO: remove. only for testing
			// UserPreferences.saveUserPrefs(this, "zzz@zzz.com",
			// Constants.TEST_TOKEN, "Test Test", "qwertyui");
			// regstrForm.setVisibility(View.GONE);
			regstrForm.setVisibility(View.VISIBLE);
			tabBar.setVisibility(View.GONE);
			tabHost.setVisibility(View.GONE);
		}
		
		tabHost.setOnTabChangedListener(this);
	}

	public void signOut() {
		regstrForm.setVisibility(View.VISIBLE);
		tabBar.setVisibility(View.GONE);
		getTabHost().setVisibility(View.GONE);
	}

	public void switchToTab(String tabName) {
		if (tabName == null)
			return;
		String currentTab = getTabHost().getCurrentTabTag();
		if (currentTab != null && currentTab.compareTo(tabName) == 0)
			return;

		getTabHost().setCurrentTabByTag(tabName);
	}

	@Override
	protected void onStop() {
		ExtLogger.getInstance().commitLog();
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		String tab = null;
		int id = v.getId();

		if (id == R.id.reg_btn_cancel) {
			llLoginContainer.setVisibility(View.VISIBLE);
			llRegContainer.setVisibility(View.GONE);
			return;
		} else if (id == R.id.login_btn) {
			String email = null, pass = null;
			if (TextUtils.isEmpty(etLoginEmail.getText())) {
				Toast.makeText(this, "Enter the email!", Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				email = etLoginEmail.getText().toString();
			}
			if (TextUtils.isEmpty(etLoginPassword.getText())) {
				Toast.makeText(this, "Enter the password!", Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				pass = etLoginPassword.getText().toString();
			}
			new LoginTask().execute(email, pass);
			return;
		} else if (id == R.id.register_btn) {
			llLoginContainer.setVisibility(View.GONE);
			llRegContainer.setVisibility(View.VISIBLE);
			return;
		} else if (id == R.id.reg_btn_register) {
			String email = null, pass = null, confirm = null, firstname = null, lastname = null;
			if (TextUtils.isEmpty(etEmail.getText())) {
				Toast.makeText(this, "Enter the email!", Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				email = etEmail.getText().toString();
			}
			if (TextUtils.isEmpty(etPassword.getText())) {
				Toast.makeText(this, "Enter the password!", Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				pass = etPassword.getText().toString();
			}
			if (TextUtils.isEmpty(etConfirm.getText())) {
				Toast.makeText(this, "Confirm the password!",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				confirm = etConfirm.getText().toString();
			}
			if (TextUtils.isEmpty(etFirstname.getText())) {
				Toast.makeText(this, "Fill in all the fields, please!",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				firstname = etFirstname.getText().toString();
			}
			if (TextUtils.isEmpty(etLastname.getText())) {
				Toast.makeText(this, "Fill in all the fields, please!",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				lastname = etLastname.getText().toString();
			}
			if (!pass.equals(confirm)) {
				Toast.makeText(this,
						"You must confirm your password porperly!",
						Toast.LENGTH_SHORT).show();
				return;
			}

			new RegisterTask().execute(email, pass, firstname, lastname);

			return;
		}

		if (id == R.id.tab_home)
			tab = TAB_HOME;
		else if (id == R.id.tab_listing)
			tab = TAB_LISTING;
		else if (id == R.id.tab_map)
			tab = TAB_MAP;
		else if (id == R.id.tab_settings)
			tab = TAB_SETTINGS;
		else if (id == R.id.tab_more)
			tab = TAB_MORE;

		switchToTab(tab);

		((TabBarButton) findViewById(R.id.tab_home)).setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_listing))
				.setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_map)).setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_settings))
				.setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_more)).setTabButtonPressed(false);

		((TabBarButton) v).setTabButtonPressed(true);
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		super.onRestoreInstanceState(state);
		int tabId = R.id.tab_home;
		if (currentTag == 1)
			tabId = R.id.tab_listing;
		else if (currentTag == 2)
			tabId = R.id.tab_map;
		else if (currentTag == 3)
			tabId = R.id.tab_settings;
		else if (currentTag == 4)
			tabId = R.id.tab_more;
		((TabBarButton) findViewById(tabId)).setTabButtonPressed(true);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		currentTag = getTabHost().getCurrentTab();
		super.onSaveInstanceState(outState);
	}

	public void setPost(ArrayList<PostModel> posts) {
		this.posts = posts;
		if (observers != null && observers.size() > 0) {
			for (OnPostListChangedListener obj : observers) {
				obj.onPostListChanged(posts);
			}
		}
	}

	public void setReporters(ArrayList<Reporter> reporters) {
		this.reporters = reporters;
		if (reporters != null && reporterListener != null) {
			reporterListener.onReporterChanged(reporters);
		}
	}

	public ArrayList<PostModel> getPosts() {
		return this.posts;
	}

	public ArrayList<Reporter> getReporters() {
		return this.reporters;
	}

	public void setOnReportersListener(OnReporterChangedListener listener) {
		this.reporterListener = listener;
	}

	public void setTempPost(PostModel post) {
		this.tempPost = post;
		if (post != null) {
			if (postItemSelListener != null) {
				postItemSelListener.onPostItemSelected(post);
			}
		}
	}

	public PostModel getTempPost() {
		return tempPost;
	}

	public void notifyObservers() {
		// handle Refresh menu item
		if (observers != null && observers.size() > 0) {
			for (OnPostListChangedListener obj : observers) {
				obj.onPostListChanged(this.posts);
			}
		}
	}

	public void switchToMapTab() {
		switchToTab(TAB_MAP);

		((TabBarButton) findViewById(R.id.tab_home)).setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_listing)).setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_map)).setTabButtonPressed(true);
		((TabBarButton) findViewById(R.id.tab_settings)).setTabButtonPressed(false);
		((TabBarButton) findViewById(R.id.tab_more)).setTabButtonPressed(false);

	}

	@Override
	public void onTabChanged(String tabId) {
		if (tabId.equals(TAB_LISTING) || tabId.equals(TAB_MAP)) {
			String type = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getString(SettingsActivity.SEARCH_AREA_KEY, null);
			if (type == null) return;
			if ((this.getAmbushType != null && !this.getAmbushType.equals(type)) || (this.getAmbushType == null)) {
				makeRequestForPostsListWithType(type);
			}
		}
	}

	public void addObserver(OnPostListChangedListener listener) {
		if (observers == null) {
			observers = new ArrayList<MainActivity.OnPostListChangedListener>();
		}
		observers.add(listener);
	}

	public void removeObserver(OnPostListChangedListener listener) {
		observers.remove(listener);
	}

	public void setOnPostItemSelectedListener(
			OnPostItemSelectedListener listener) {
		this.postItemSelListener = listener;
	}

	// Location code
	private String getAmbushType = null;

	public void makeRequestForPostsListWithType(String type) {
		getAmbushType = type;
		mlManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		if (pdBar != null) {
			pdBar.setMessage("Updating location...");
			pdBar.show();
		}
	}

	public void makeRequestForTopReporters() {
		new TopReportersLoadTask().execute();
	}

	@Override
	public void onLocationChanged(Location location) {
		new PostLoaderTask(getAmbushType).execute(location);
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	private class TopReportersLoadTask extends
			AsyncTask<Void, Void, ArrayList<Reporter>> {
		@Override
		protected void onPostExecute(ArrayList<Reporter> param) {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.dismiss();
			}
			MainActivity.this.setReporters(param);
		}

		@Override
		protected void onPreExecute() {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.setMessage("Updating top rerorters list...");
			} else if (pdBar != null) {
				pdBar.show();
			}
		}

		@Override
		protected ArrayList<Reporter> doInBackground(Void... params) {
			String token = UserPreferences.getUserToken(MainActivity.this);
			String url = String.format(Constants.API_GET_TOP_REPORTERS, token);
			String output = ServiceManager.performRequest(url);
			return CustomXmlParser.parseXmlForTopReporters(output);
		}
	}

	private class PostLoaderTask extends
			AsyncTask<Location, Void, ArrayList<PostModel>> {

		String requestType;

		public PostLoaderTask(String requestType) {
			this.requestType = requestType;
		}

		@Override
		protected void onPostExecute(ArrayList<PostModel> param) {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.dismiss();
			}
			MainActivity.this.setPost(param);
		}

		@Override
		protected void onPreExecute() {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.setMessage("Updating list...");
			} else if (pdBar != null) {
				pdBar.show();
			}
		}

		@Override
		protected ArrayList<PostModel> doInBackground(Location... params) {
			mlManager.removeUpdates(MainActivity.this);
			// request for list of posts
			String requestUrl = null;
			// TODO:
			String token = UserPreferences.getUserToken(MainActivity.this);
			Location lct = params[0];
			float latitude = (float) lct.getLatitude();
			float longitude = (float) lct.getLongitude();
			if (Constants.GET_TYPE_DENMARK.equalsIgnoreCase(requestType)) {
				requestUrl = String.format(Constants.API_GET_DK_AMBUSHES,
						token, latitude, longitude);
			} else {
				String rIM = PreferenceManager.getDefaultSharedPreferences(
						MainActivity.this).getString(
						SettingsActivity.RADIUS_KEY, "1000");
				float radiusInMeters = Float.parseFloat(rIM);
				float radius = ((float) radiusInMeters) / 1000f;
				requestUrl = String.format(Constants.API_GET_NEARBY_AMBUSHES,
						token, latitude, longitude, radius);
			}

			String output = ServiceManager.performRequest(requestUrl);
			ArrayList<PostModel> items = CustomXmlParser
					.parseXmlForPostList(output);

			return items;
		}

	}

	public void onRegistered() {
		Toast.makeText(this, "Welcome to the Fartkontrollerne.",
				Toast.LENGTH_SHORT).show();
		regstrForm.setVisibility(View.GONE);
		tabBar.setVisibility(View.VISIBLE);
		getTabHost().setVisibility(View.VISIBLE);
	}

	private class RegisterTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPostExecute(Boolean param) {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.dismiss();
			}
			if (param) {
				onRegistered();
			} else {
				Toast.makeText(MainActivity.this,
						"Registration failed. Try again, please.",
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			if (pdBar != null) {
				pdBar.setMessage("Registering...");
				if (!pdBar.isShowing())
					pdBar.show();
			}
		}

		@Override
		protected Boolean doInBackground(String... params) {
			String registerUrl = String.format(Constants.API_REGISTER_NEW_USER,
												params[0], params[1], params[2], params[3]);
			boolean result = ServiceManager.requestForRegisterUser(registerUrl);
			ExtLogger.getInstance().writeLog(new Date(), "Main.RegisterTask","Try to register...");
			if (result) {
				ExtLogger.getInstance().writeLog(new Date(), "Main.RegisterTask", "Successful registration");
				UserPreferences.saveUserPrefs(MainActivity.this, params[0], null, params[2] + " " + params[3], params[1]);
				String newTokenRequest = String.format(Constants.API_GET_TOKEN,params[0], params[1]);
				String token = ServiceManager.requestForUserToken(newTokenRequest);
				UserPreferences.saveUserToken(MainActivity.this, token);
			}
			return result;
		}
	}

	private class LoginTask extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPostExecute(Void param) {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.dismiss();
			}
			if (((FApplication) MainActivity.this.getApplication()).isLogged()) {
				onRegistered();
			} else {
				Toast.makeText(MainActivity.this,
						"Login failed. Try again,please", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		protected void onPreExecute() {
			if (pdBar != null) {
				pdBar.setMessage("Loggin On...");
				if (!pdBar.isShowing())
					pdBar.show();
			}
		}

		@Override
		protected Void doInBackground(String... params) {
			// get new token and save it
			String email = params[0];
			String password = params[1];
			String newTokenRequest = String.format(Constants.API_GET_TOKEN, email, password);
			String newToken = ServiceManager.requestForUserToken(newTokenRequest);
			if (!TextUtils.isEmpty(newToken)) {
				UserPreferences.saveUserPrefs(MainActivity.this, params[0], newToken, null, params[1]);
				((FApplication) MainActivity.this.getApplication()).setLogged(true);
				ExtLogger.getInstance().writeLog(new Date(), "Main.LoginTask","Got new token!");
			} else {
				((FApplication) MainActivity.this.getApplication()).setLogged(false);
				ExtLogger.getInstance().writeLog(new Date(), "Main.LoginTask","Failed to get new token");
			}

			return null;
		}
	}

	private class GetTokenTask extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPostExecute(Void param) {
			if (pdBar != null && pdBar.isShowing()) {
				pdBar.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			if (pdBar != null) {
				pdBar.setMessage("Loggin On...");
				if (!pdBar.isShowing())
					pdBar.show();
			}
		}

		@Override
		protected Void doInBackground(String... params) {
			String token = UserPreferences.getUserToken(MainActivity.this);
			/*if (!TextUtils.isEmpty(token)) {
				// check token
				String checkTokenUrl = String.format(
						Constants.API_CHECK_TOKEN_IS_VALID, token);
				if (!ServiceManager.requestForTokenIsValid(checkTokenUrl)) {
					// get new token and save it
					String email = UserPreferences
							.getUserEmail(MainActivity.this);
					String password = UserPreferences
							.getUserPassword(MainActivity.this);
					String newTokenRequest = String.format(
							Constants.API_GET_TOKEN, email, password);
					String newToken = ServiceManager
							.requestForUserToken(newTokenRequest);
					if (!TextUtils.isEmpty(newToken)) {
						UserPreferences.saveUserToken(MainActivity.this,
								newToken);
						((FApplication) MainActivity.this.getApplication())
								.setLogged(true);
					} else {
						((FApplication) MainActivity.this.getApplication())
								.setLogged(false);
					}
				}
			} else {*/
				// get new token and save it
				String email = UserPreferences.getUserEmail(MainActivity.this);
				String password = UserPreferences
						.getUserPassword(MainActivity.this);
				String newTokenRequest = String.format(Constants.API_GET_TOKEN,
						email, password);
				String newToken = ServiceManager
						.requestForUserToken(newTokenRequest);
				if (!TextUtils.isEmpty(newToken)) {
					UserPreferences.saveUserToken(MainActivity.this, newToken);
					((FApplication) MainActivity.this.getApplication())
							.setLogged(true);
				} else {
					((FApplication) MainActivity.this.getApplication())
							.setLogged(false);
				}
			/*}*/

			return null;
		}
	}

	/**
	 * Determines whether one Location reading is better than the current
	 * Location fix
	 * 
	 * @param location
	 *            The new Location that you want to evaluate
	 * @param currentBestLocation
	 *            The current Location fix, to which you want to compare the new
	 *            one
	 */
	protected boolean isBetterLocation(Location location,
			Location currentBestLocation) {
		if (currentBestLocation == null) {
			// A new location is always better than no location
			return true;
		}

		// Check whether the new location fix is newer or older
		long timeDelta = location.getTime() - currentBestLocation.getTime();
		boolean isSignificantlyNewer = timeDelta > A_MINUTE;
		boolean isSignificantlyOlder = timeDelta < -A_MINUTE;
		boolean isNewer = timeDelta > 0;

		// If it's been more than two minutes since the current location, use
		// the new location
		// because the user has likely moved
		if (isSignificantlyNewer) {
			return true;
			// If the new location is more than two minutes older, it must be
			// worse
		} else if (isSignificantlyOlder) {
			return false;
		}

		// Check whether the new location fix is more or less accurate
		int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
				.getAccuracy());
		boolean isLessAccurate = accuracyDelta > 0;
		boolean isMoreAccurate = accuracyDelta < 0;
		boolean isSignificantlyLessAccurate = accuracyDelta > 200;

		// Check if the old and new location are from the same provider
		boolean isFromSameProvider = isSameProvider(location.getProvider(),
				currentBestLocation.getProvider());

		// Determine location quality using a combination of timeliness and
		// accuracy
		if (isMoreAccurate) {
			return true;
		} else if (isNewer && !isLessAccurate) {
			return true;
		} else if (isNewer && !isSignificantlyLessAccurate
				&& isFromSameProvider) {
			return true;
		}
		return false;
	}

	/** Checks whether two providers are the same */
	private boolean isSameProvider(String provider1, String provider2) {
		if (provider1 == null) {
			return provider2 == null;
		}
		return provider1.equals(provider2);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DLG_CANCEL_REGISTRATION:
			AlertDialog.Builder b1 = new Builder(this);
			b1.setTitle("Abort registration")
					.setMessage(
							"You are cancelling the registration. Only registered users can use the app. Continue?")
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									MainActivity.this
											.showDialog(DLG_ACCESS_DENIED);
								}
							});
			return b1.create();
		case DLG_ACCESS_DENIED:
			AlertDialog.Builder b2 = new Builder(this);
			b2.setTitle("Access denied!")
					.setMessage("Only registered users can use the app.")
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									MainActivity.this.finish();
								}
							});
			return b2.create();
		}
		return null;
	}

}